package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.val;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
@Autowired
private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
   @Autowired
private WorkspaceService workspaceService;
//统计指定营业额数据
    @Override
    public TurnoverReportVO Gettrunoverstatistics(LocalDate begin, LocalDate end) {
        //存放时间数据
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){   //日期计算从指定日期到最后一天日期
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //存放每天的营业额数据
        List<Double>turnoverList=new ArrayList<>();
        //查询对应数时间已完成的营业额
        for(LocalDate date:dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MAX);
            LocalDateTime enderTime = LocalDateTime.of(date, LocalTime.MIN);
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",enderTime);
            map.put("status", Orders.COMPLETED);
            Double turnover=orderMapper.sumByMap(map);
            turnover=turnover==null?0.0:turnover;
            turnoverList.add(turnover);
            //查询select sum(count) from orders where order_Time>? and order_Time<? and status=5;
        }


        return  TurnoverReportVO
                .builder().dateList(StringUtils.join(dateList,","))
                . turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    @Override
    public UserReportVO Getusertatistics(LocalDate begin, LocalDate end) {
        //存放时间数据
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){   //日期计算从指定日期到最后一天日期
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //存放新增用戶数据
        List<Integer>newUserList=new ArrayList<>();
        //存放所有用户数据
        List<Integer>totalUserList=new ArrayList<>();
        for(LocalDate date:dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MAX);
            LocalDateTime enderTime = LocalDateTime.of(date, LocalTime.MIN);
            Map map = new HashMap();
            map.put("end", enderTime);
        Integer sumuser=userMapper.userMap(map); //总数量
            map.put("begin",beginTime);
        Integer  newuser=userMapper.userMap(map);//新增数量
            newUserList.add(newuser);
            totalUserList.add(sumuser);

        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }
//统计指定时间的订单数据
    @Override
    public OrderReportVO Getorderstatistics(LocalDate begin, LocalDate end) {
        //存放时间数据
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){   //日期计算从指定日期到最后一天日期
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //所以订单数据
        List<Integer>ordercountlist=new ArrayList<>();
        //完成订单数据
        List<Integer>validorderlist=new ArrayList<>();
         //查询每天订单完成数据
        for(LocalDate date:dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MAX);
            LocalDateTime enderTime = LocalDateTime.of(date, LocalTime.MIN);
            //查看订单总数
             Integer ordercount=  getorderCount(beginTime,enderTime,null);
            //查看有效订
            Integer  validorder= getorderCount(beginTime,enderTime,5);
            ordercountlist.add(ordercount);
            validorderlist.add(validorder);

        }
        //计算订单数量
        Integer totalOrderCount=ordercountlist.stream().reduce(Integer::sum).get();
        //计算有效订单数量
        Integer validOrderCount=validorderlist.stream().reduce(Integer::sum).get();
   //计算订单完成率
        Double orderCompletionRate=0.0;
        if(totalOrderCount!=0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount.doubleValue();
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(ordercountlist,","))
                .validOrderCountList(StringUtils.join(validorderlist,","))
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO GetTop10(LocalDate begin, LocalDate end) {

            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MAX);
            LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MIN);

            //查看前10菜品
            List<GoodsSalesDTO> salesTop10=orderMapper.getordertop10(beginTime,endTime);

//select od.name, sum(od.num) from order_detail od,order o  where  o.order_time>?and end<? and od.order.id=o.id and o.status=5 group by od.name order by num desc limit 0,10;
List<String> names= salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
  String nameList=StringUtils.join(names,",");
  List<Integer>  nameber =salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
  String nameberList=StringUtils.join(nameber);

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(nameberList)
                .build();


    }


    private Integer getorderCount(LocalDateTime begin, LocalDateTime end, Integer status){
       Map map=new HashMap<>();
            map.put("end", end);
            map.put("begin",begin);
            map.put("status",status);


            return orderMapper.countOrder(map);
    }

    public void exportBusinessDAta(HttpServletResponse response){
              //查询数据库，获取营业数据-- 最近30天
        LocalDate   dateBegin=LocalDate.now().minusDays(30);
        LocalDate   dateend=LocalDate.now().minusDays(1);
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateend, LocalTime.MAX));
        //通过POI将数据写入Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("tamplate/运营数据报表模版.xlsx");
        //基于模版文件创建一个新的Excel
        try {
            XSSFWorkbook excel=new XSSFWorkbook(in);
            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("sheet1");
            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间： "+dateBegin+"至"+dateend);
            //填充第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
             row.getCell(6).setCellValue(businessDataVO.getNewUsers());
                  //填充第5行
            XSSFRow row2 = sheet.getRow(4);
            row2.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row2.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            for (int i = 0; i < 30; i++) {
                LocalDate date=dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
               //获取某一行
                row=sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }


            // 通过输入流将excel文件导入客服端
            ServletOutputStream out=response.getOutputStream();
            excel.write(out);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }




    }






















}
